import { ref, computed } from 'vue'
import { LOADING_STATES } from '../constants'

/**
 * 加载状态管理组合式函数
 * @param {string} initialState 初始状态
 * @returns {Object} 加载状态和方法
 */
export function useLoading(initialState = LOADING_STATES.IDLE) {
  const state = ref(initialState)
  const message = ref('')
  const progress = ref(0)

  const isLoading = computed(() => state.value === LOADING_STATES.LOADING)
  const isIdle = computed(() => state.value === LOADING_STATES.IDLE)
  const isSuccess = computed(() => state.value === LOADING_STATES.SUCCESS)
  const isError = computed(() => state.value === LOADING_STATES.ERROR)

  const setLoading = (msg = '加载中...') => {
    state.value = LOADING_STATES.LOADING
    message.value = msg
    progress.value = 0
  }

  const setSuccess = (msg = '操作成功') => {
    state.value = LOADING_STATES.SUCCESS
    message.value = msg
    progress.value = 100
  }

  const setError = (msg = '操作失败') => {
    state.value = LOADING_STATES.ERROR
    message.value = msg
    progress.value = 0
  }

  const setIdle = () => {
    state.value = LOADING_STATES.IDLE
    message.value = ''
    progress.value = 0
  }

  const setProgress = (value) => {
    progress.value = Math.max(0, Math.min(100, value))
  }

  const reset = () => {
    setIdle()
  }

  return {
    // 状态
    state: readonly(state),
    message: readonly(message),
    progress: readonly(progress),
    
    // 计算属性
    isLoading,
    isIdle,
    isSuccess,
    isError,
    
    // 方法
    setLoading,
    setSuccess,
    setError,
    setIdle,
    setProgress,
    reset
  }
}



